/**
 * get  promise-ajax封装
 * @param {string} url 请求地址
 * @param {object} params 请求参数
 * @param {string} type 请求参数
 * @param {object} header  自定义请求头
 * @returns promise
 */
function get(url, params, type, header = {}) {
    let temp = []
    for (let key in params) {
        temp.push(`${key}=${params[key]}`)
    }
    let paramFilter = temp.join('&')
    let p = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    let res = xhr.responseText
                    if (type === 'json') res = JSON.parse(res)
                    resolve(res)
                } else {
                    reject(xhr.status)
                }
            }
        }
        xhr.open('get', `${url}?${paramFilter}`)
        for (let key in header) {
            xhr.setRequestHeader(key, header[key])
        }
        xhr.send(null)

    })
    return p
}

/**
 * post  promise-ajax封装
 * @param {string} url 请求地址
 * @param {object} params 请求参数
 * @param {string} type 请求参数
 * @param {object} header  自定义请求头
 * @returns promise
 */
function post(url, params, type, header = {}) {
    let temp = []
    for (let key in params) {
        temp.push(`${key}=${params[key]}`)
    }
    let paramFilter = temp.join('&')
    let p = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    let res = xhr.responseText
                    if (type === 'json') res = JSON.parse(res)
                    resolve(res)
                } else {
                    reject(xhr.status)
                }
            }
        }
        xhr.open('post', url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        for (let key in header) {
            xhr.setRequestHeader(key, header[key])
        }
        xhr.send(paramFilter)

    })
    return p
}

export { get, post }


